package org.dwpd.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.dwpd.domain.common.Result;
import org.dwpd.domain.user.UserDTO;
import org.dwpd.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * Package:org.dwpd.interceptor
 *
 * @ClassName:LoginInterceptor
 * @Create:2024/8/16 15:51
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;
    public LoginInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从UserHolder中获取userDTO判断是否登录
        UserDTO userDTO = UserHolder.getUser();
        if (userDTO == null){
            Result fail = Result.fail(-2, "用户未登录");
            ObjectMapper objectMapper = new ObjectMapper();
            String string = objectMapper.writeValueAsString(fail);
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter printWriter = null;
            try {
                printWriter = response.getWriter();
                printWriter.print(string);
                printWriter.flush();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                if (printWriter != null) {
                    printWriter.close();
                }
            }
            //拦截
            return false;
        }
        //放行
        return true;
    }
}
